package com.khyr.service.impl;

import com.khyr.dao.MenuDao;
import com.khyr.entity.Menu;
import com.khyr.service.MenuService;
import com.khyr.vo.R;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuDao menuDao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private HttpServletRequest request;
    @Override
    public R<List<Menu>> getByUserId(Long userId) {
        List<Menu> menus = menuDao.selectByUserId(userId);
        return new R<List<Menu>>(200,"查询成功",menus);
    }

    @Override
    //获取左侧菜单栏
    public R<List<Menu>> selectLeftMenuByUserId() {
        //获取token
        String token = request.getHeader("token");
        //根据token获取手机号
        Object phone = redisTemplate.opsForHash().get("user::login::" + token, "name");
        //根据手机号查询当前用户的权限
        List<Menu> menus = menuDao.selectLeftMenuByPhone(phone);
        //查询一级菜单
        List<Menu> firsts = menus.stream().filter(item -> item.getParentId().equals(0L)).collect(Collectors.toList());
        //查询对应的二级菜单
        for(Menu first:firsts){
            List<Menu> children=new ArrayList<>();
            for(Menu m:menus){
                if(first.getMenuId().equals(m.getParentId())){
                    children.add(m);
                }
            }
            first.setChildren(children);
        }

        return new R<List<Menu>>(200,"查询成功",firsts);
    }

}
